package com.putong35.easyui.ric;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayout;
import com.putong35.common.utils.DimensionUtil;
import com.putong35.common.utils.EasyToast;
import com.putong35.easyui.R;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;


/**
 * Simple to Introduction
 *
 * @Author: PengWeiwei
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017-04-11
 * @Version: 1.0.0
 */
public class PickPictureFragment extends Fragment implements ActivityCompat.OnRequestPermissionsResultCallback{

    Adapter adapter = new Adapter();

    FlexboxLayout flxContainer;
    PictureChooseHelper pictureChooseHelper;

    public PickPictureFragment() {
        // Required empty public constructor
    }

    public static PickPictureFragment newInstance() {
        PickPictureFragment fragment = new PickPictureFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    public int getPicSize() {
        return adapter.dataList.size();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ric_fragment_pick_picture, container, false);
        flxContainer = (FlexboxLayout) view.findViewById(R.id.flxContainer);
        pictureChooseHelper = new PictureChooseHelper(this,
                new PictureChooseHelper.OnPictureReturnSuccessListener() {
                    @Override
                    public void OnPictureReturnSuccess(View srcView, String... urls) {
                        Log.e("urls.length", "" + urls.length);
                        if (urls != null && urls.length > 0) {
                            for (String url : urls) {
                                Log.e("urlurl", "" + url);
                                adapter.dataList.add(url);
                            }
                            adapter.notifyDataChange();
                            setMaxPic(pictureChooseHelper.maxPicForChoose - urls.length);
                        }
                    }
                },
                new PictureChooseHelper.OnPictureReturnFailureListener() {
                    @Override
                    public void OnPictureReturnFailure(View srcView, Throwable t, int errorNo, String strMsg) {
                        EasyToast.showToast(getActivity(), "图片上传失败！");
                    }
                }, 9);

        adapter.setTargetView(getContext(), flxContainer);

        return view;
    }

    public void setMaxPic(int size) {
        pictureChooseHelper.setMaxPic(size);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        pictureChooseHelper.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        pictureChooseHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public List<String> getSelectedPictureUrls() {
        return adapter.dataList();
    }

    public void setPics(List<String> pics) {
        adapter.dataList = pics;
        adapter.notifyDataChange();
    }


    public class Adapter {

        public static final int TYPE_ADD = 0;
        public static final int TYPE_IMG = 1;

        List<String> dataList = new ArrayList<>();

        public Context context;
        public FlexboxLayout flexContainer;

        public void setTargetView(Context context, FlexboxLayout layout) {
            this.context = context;
            this.flexContainer = layout;
            notifyDataChange();
        }

        void notifyDataChange() {
            flexContainer.removeAllViews();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
            int count = getCount();

            for (int i = 0; i < count; i++) {
                View view = getView(inflater, i);
                flexContainer.addView(view);
            }
        }


        int getCount() {
            if (dataList == null) {
                return 1;
            } else {
                return dataList.size() + 1;
            }
        }

        int getType(int position) {
            // 最后一个位置放添加图片的图标
            if (dataList != null && dataList.size() == position) {
                return TYPE_ADD;
            } else {
                return TYPE_IMG;
            }
        }


        View getView(LayoutInflater inflater, final int posi) {
            float defWidthDip = DimensionUtil.getScreenWidthDip() - 16;
            int defWidth = DimensionUtil.dip2px(context, defWidthDip) / 5;
            int defHeight = defWidth;

            if (getType(posi) == TYPE_ADD) {
                View itemView = inflater.inflate(R.layout.ric_grid_item_release_image_content, null);
                itemView.findViewById(R.id.btnDelete).setVisibility(View.GONE);
                itemView.setLayoutParams(new FlexboxLayout.LayoutParams(defWidth, defHeight));
                pictureChooseHelper.addTargetView(itemView);
                return itemView;
            } else {
                View itemView = inflater.inflate(R.layout.ric_grid_item_release_image_content, null);
                itemView.setLayoutParams(new FlexboxLayout.LayoutParams(defWidth, defHeight));
                ImageView imageView = (ImageView) itemView.findViewById(R.id.ivImage);
                Glide.with(context).load(dataList.get(posi)).into(imageView);
                ImageButton btn = (ImageButton) itemView.findViewById(R.id.btnDelete);
                btn.setVisibility(View.VISIBLE);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        delete(posi);
                    }
                });
                return itemView;
            }
        }


        void delete(int posi) {
            dataList.remove(posi);
            pictureChooseHelper.setMaxPic(pictureChooseHelper.maxPicForChoose - 1);
            notifyDataChange();
        }

        void add(String url) {
            dataList.add(url);
            notifyDataChange();
        }

        List<String> dataList() {
            return dataList;
        }

    }


}
